package com.shuiyun.chat.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuiyun.chat.client.ChatClient;
import com.shuiyun.chat.config.NettyConfig;
import com.shuiyun.chat.entity.bo.SendMsgBO;
import com.shuiyun.chat.entity.bo.UserBO;
import com.shuiyun.chat.entity.bo.UserUpdateBO;
import com.shuiyun.chat.entity.message.LoginRequestMessage;
import com.shuiyun.chat.entity.message.LoginResponseMessage;
import com.shuiyun.chat.entity.message.SimpleChatMessage;
import com.shuiyun.chat.entity.po.UserPO;
import com.shuiyun.chat.entity.vo.UserVO;
import com.shuiyun.chat.mapper.UserMapper;
import com.shuiyun.chat.utils.BeanUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shuiyun
 * @since 2021-05-12
 */
@Slf4j
@Service
public class UserService extends ServiceImpl<UserMapper, UserPO> {

    @Autowired
    UserMapper userMapper;

    private Map<String, Channel> userNameChannelMap = null;
    private Map<Channel,UserVO> channelUserNameMap = null;

    @Autowired
    private NettyConfig.NettyClientConfig clientConfig;
    @Autowired
    private ClientService clientService;

    public UserService(){
        userNameChannelMap = new HashMap<>();
        channelUserNameMap = new HashMap<>();
    }

    /**
     * <p>
    * 通过ID获取对象
    * </p>
     *
     */
    public UserVO get(Long id) {
        return BeanUtil.copyProperties(userMapper.selectById(id), UserVO.class);
    }

    /**
     * <p>
    * 新增对象
    * </p>
     *
     */
    public Object add(UserBO userBO) {
        UserPO user = new UserPO();
        BeanUtil.copyProperties(userBO, user);
        userMapper.insert(user);
        return user.getId();
    }

    /**
     * <p>
    * 修改对象
    * </p>
     *
     */
    public void update(UserUpdateBO userUpdateBO) {
        userMapper.updateById(BeanUtil.copyProperties(userUpdateBO, UserPO.class));
    }

    /**
     * <p>
    * 删除对象
    * </p>
     *
     */
    public void delete(Long id) {
        userMapper.deleteById(id);
    }


    /**
     *根据用户名查询用户信息
     * @param userName 用户名
     * @Author: shuiyun
     * @Date: 2021/5/12 21:56
     * @return 用户信息
     */
    public UserVO findByUserName(String userName) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<UserPO>().eq("user_name",userName);
        UserPO po = this.getOne(queryWrapper);
        return BeanUtil.copyProperties(po,UserVO.class);
    }

    public void bind(UserVO user, Channel channel){
        userNameChannelMap.put(user.getUserName(),channel);
        channelUserNameMap.put(channel,user);
    }

    public UserVO getUserByChannel(Channel channel){
        return channelUserNameMap.get(channel);
    }

    public Channel getChannelByUserName(String userName){
        return userNameChannelMap.get(userName);
    }

    /**
     *
     * @param
     * @Author: shuiyun
     * @Date: 2021/5/12 22:54
     * @return
     */
    public LoginResponseMessage login(UserBO userBO)  {
        CountDownLatch wait = new CountDownLatch(1);
        ChatClient client = new ChatClient(wait);
        Channel channel = client.connect(clientConfig.getTcpIp(), clientConfig.getTcpPort());
        channel.writeAndFlush(new LoginRequestMessage(userBO.getUserName(),userBO.getPassword(),userBO.getNickName()));
        // 等待返回登录结果唤醒主程序
        try {
            wait.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LoginResponseMessage loginMessage = client.getLoginMessage();
        // 如果登录失败 则关闭连接 等待下一次连接 如果成功则保存通道信息
        if (loginMessage.getSuccess()){
            clientService.online(userBO.getUserName(),channel);
        }else{
            channel.close();
        }
        // 如果登录成功 则缓存当前通道
        return loginMessage;
    }

}
